package com.sudo.api._admin;

import com.sudo.common.annotation.ApiIdempotent;
import com.sudo.common.annotation.ApiAuthorization;
import com.sudo.common.constant.SysConfigConstant;
import com.sudo.common.utils.HttpUserInfoUtil;
import com.sudo.common.utils.JsonRes;
import com.sudo.dao.admin.model.bo.sysconfig.SysUserRegistBO;
import com.sudo.service.admin.service.SysConfigService;
import com.sudo.service.admin.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@Slf4j
@Api(value = "系统配置",tags = {"系统配置相关的接口"})
@RestController
@RequestMapping("sysConfig")
public class SysConfigController extends AdminBaseController {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysConfigService sysConfigService;

    @ApiOperation(value = "查询用户注册配置",notes = "查询用户注册配置",httpMethod = "GET")
    @GetMapping("getUserRegistCfg")
    public JsonRes getUserRegistCfg() {
        Map<String,String> userRegistMap = sysConfigService.getSysConfigMapByObject(SysConfigConstant.USER_REGIST);
        return JsonRes.ok(userRegistMap);
    }


    @ApiIdempotent
    @ApiAuthorization(menu = "sys_config",button = "userRegistUpdate")
    @ApiOperation(value = "修改用户注册配置",notes = "修改用户注册配置",httpMethod = "POST")
    @PostMapping("updateUserRegistCfg")
    public JsonRes updateUserRegistCfg(HttpServletRequest request,
                                       @RequestBody @Valid SysUserRegistBO sysUserRegistBO,
                                       BindingResult result) {
        //验证
        if (result.hasErrors()) {
            return JsonRes.errorMsg(getFirstError(result));
        }
        // 验证注册角色是否存在
        boolean hasRegistRole = sysRoleService.hasRoleCode(sysUserRegistBO.getRegist_role());
        if (!hasRegistRole) {
            return JsonRes.errorMsg("注册角色不存在");
        }
        // 验证过期角色是否存在
        boolean hasExpiryRole = sysRoleService.hasRoleCode(sysUserRegistBO.getExpiry_role());
        if (!hasExpiryRole) {
            return JsonRes.errorMsg("过期角色不存在");
        }

        String sessionUser = HttpUserInfoUtil.getSessionUser(request);
        Map<String, String> stringMap = sysUserRegistBO.bean2Map(sessionUser,sysUserRegistBO);
        int affectCount = sysConfigService.updateValueByObjectKey(SysConfigConstant.USER_REGIST,stringMap);
        return JsonRes.judge(affectCount,"修改用户注册配置成功","修改用户注册配置失败");
    }
}
